package com.fy.core.upload;

import cn.hutool.json.JSONUtil;
import com.fy.core.vo.ApiRest;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@CrossOrigin
public class UploadController {


    @Autowired
    private QiniuProperties qiniuProperties;


    @PostMapping("/upload")
    @ResponseBody
    public ApiRest upload(MultipartFile img){

        try {
            byte[] bytes = img.getBytes();
            String originalFilename = img.getOriginalFilename();
            System.out.println("originalFilename = " + originalFilename);

            //落地(1：fastdfs文件系统 、2：oss【object storage server】七牛云云存储服务器)

            // Region必须指定为bucket设置的地址
            Configuration cfg = new Configuration(Region.huanan());
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
            UploadManager uploadManager = new UploadManager(cfg);


            String key = null;
            //获取令牌
            Auth auth = Auth.create(qiniuProperties.getAk(), qiniuProperties.getSk());
            String upToken = auth.uploadToken(qiniuProperties.getBucket());
            Response response = uploadManager.put(bytes, key, upToken);
            String jsonStr = response.bodyString();

            //json  -> java对象
            DefaultPutRet obj = JSONUtil.toBean(jsonStr, DefaultPutRet.class);
            //上传成功后的的文件名
            String url = qiniuProperties.getHost()+obj.key;
            System.out.println("url = " + url);
            //save url to db

            return ApiRest.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return ApiRest.failure();
        }




      }

}
